import React from 'react';
import { Button, Card, Row, Col } from 'antd';
import { FormComponentProps, ComponentDecorator } from 'antd/lib/form/Form';
import { Form } from 'components'
import { IFormProps } from 'components/Form/Form'
import SearchItem from './SearchItem'
import moment from 'moment'

declare type FormLayout = 'horizontal' | 'inline' | 'vertical';
interface ISearchBarProps {
	layout?: FormLayout,
	searchBarConfig: any,
	isReset?: boolean,
	footer?: string,
	searchButton?: string,
	resetButton?: string,
	onSearch?: (modal: any) => void,
}

class SearchBar extends React.Component<ISearchBarProps, any> {
	static defaultProps = {
		searchBarConfig: [],
		isReset: true,
		footer: 'right',
		searchButton: '搜索',
		resetButton: '重置',
		layout: 'inline'
	}
	formRef: any
	constructor(props: ISearchBarProps) {
		super(props);

		this.state = {
			model: {}
		}
	}
	componentDidMount() {
		let data = {};
		const { searchBarConfig } = this.props;
		searchBarConfig.forEach((RowItem: any[], rowIndex: number) => {
			RowItem.forEach((item, index) => {
				data[item.field] = ''
				const { decoratorOptions } = item
				if (decoratorOptions && decoratorOptions.initialValue)
					data[item.field] = decoratorOptions!.initialValue
			})
		})
		this.setState({ model: data })
	}

	hanldeSubmit = (data: any) => {
		const { onSearch } = this.props;
		console.log('search data:', data)
		if (onSearch)
			onSearch(data);
	}
	handleReset = () => {
		console.log('this.formRef:', this.formRef)
		this.formRef.resetFields();
	}

	render() {
		const { model } = this.state;
		const {
			searchBarConfig,
			searchButton,
			resetButton,
			isReset,
			footer,
		} = this.props;

		let footerStyle = {};
		if (footer)
			footerStyle = { 'textAlign': footer }

		return (
			<Form onSubmit={this.hanldeSubmit}
				model={model}
				layout="inline"
				ref={(formRef) => this.formRef = formRef}>
				{searchBarConfig.map((RowItem: any[], rowIndex: number) => (
					<Row
						style={{ 'marginBottom': '10px' }}
						key={rowIndex.toString()} >
						{RowItem.map((item, index) => {
							let { width, ...rest } = item;
							return (
								<SearchItem {...rest} key={index.toString()} />
							)
						})}
					</Row>
				))}
				<div style={{ display: 'block', ...footerStyle }}>
					<Button type="primary" htmlType='submit'>
						{searchButton}
					</Button>
					{isReset && (
						<Button style={{ marginLeft: '15px' }}
							onClick={this.handleReset}>
							{resetButton}
						</Button>
					)}
				</div>
			</Form>
		)
	}
}

export default SearchBar

